//
//  PLRequestManage.m
//  PL
//
//  Created by kimi on 15/7/21.
//  Copyright (c) 2015年 kimi. All rights reserved.
//

#import "PLRequestManage.h"
#import "MainNavigationController.h"
#import "LoginController.h"
#import "DataController.h"
#import "DataController+Cache.h"
#import "SystemDeviceTool.h"

@interface PLRequestManage()

@end

@implementation PLRequestManage

+ (id)sharedInstance
{
    static dispatch_once_t pred;
    static PLRequestManage *sharedInstance = nil;
    dispatch_once(&pred, ^{
        sharedInstance = [[PLRequestManage alloc] init];
    });
    return sharedInstance;
}
- (AFHTTPSessionManager *)httpManager
{
    if (!_httpManager) {
        _httpManager = [AFHTTPSessionManager manager];
        _httpManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _httpManager.requestSerializer.timeoutInterval=15.0;
//        _httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/plain",@"text/html",@"application/json",nil];
//        _httpManager.operationQueue.maxConcurrentOperationCount=10;
    }
    return _httpManager;
}

- (NSURLSessionDataTask *)httpRequestWithUrl:(NSString*)urlStr Type:(RequestType)type parameters:(NSDictionary *)params success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSURLSessionDataTask * dataTask;
    if (type == RequestGet) {
        dataTask = [self.httpManager GET:urlStr parameters:params progress:nil success:success failure:failure];
    } else {
//        [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
        dataTask = [self.httpManager POST:urlStr parameters:params progress:nil success:success failure:failure];
    }
    return dataTask;
}

- (void)httpRequestWithUrl:(NSString*)urlStr Type:(RequestType)type parameters:(NSDictionary *)params completeHandle:(void (^)(id _Nullable responseObject, NSError * error))completeHandle
{
    [self httpRequestWithUrl:urlStr Type:type parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject ) {
        NSString *message = responseObject[@"msg"];
//        NSInteger retCode = ((NSNumber *)[responseObject objectForKey:@"code"]).integerValue;
        NSInteger retCode = ((NSNumber *)[responseObject objectForKey:@"status"]).integerValue;
        switch (retCode) {
            case 0:
                completeHandle(responseObject[@"data"],nil);
                break;
            case HTTPCodeLogout: {
                [[UserLocal sharedInstance] setCurrentUserInfo:nil];
                MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
                [getDelegate().masterNavigationController presentViewController:vc animated:YES completion:nil];
                break;
            }
            case HTTPCodeOK: {
                completeHandle(responseObject,nil);
                break;
            }
            case -1:{ // 账号异地登录
                [[UserLocal sharedInstance] setCurrentUserInfo:nil];
                NSMutableDictionary * paramSocket = [NSMutableDictionary dictionary];
                paramSocket[@"macId"] = [SystemDeviceTool getUUID];
                paramSocket[@"userId"] = [[UserLocal sharedInstance] currentUserInfo].phone;
                paramSocket[@"flag"] = @(1);
                [[PLRequestManage sharedInstance] httpRequestWithUrl:WEBSOCKETWITH(url_loginWebsocket) Type:RequestPost parameters:paramSocket completeHandle:^(id  _Nullable responseObject, NSError *error) {
                    if (!error) {
                    }else{
                        
                    }
                }];
                LoginController *loginVC = [[LoginController alloc] init];
                loginVC.isRemoteLogin = YES;
                MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:loginVC];
                [getDelegate().masterNavigationController presentViewController:vc animated:YES completion:nil];
                break;
            }
            default:
                completeHandle(responseObject,[NSError errorWithDomain:@"" code:retCode userInfo:@{NSLocalizedDescriptionKey:message}]);
                break;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completeHandle(task.response,error);
    }];
}
- (void)httpRequestWithUrl:(NSString*)urlStr Type:(RequestType)type parameters:(NSDictionary *)params completeHandle:(void (^)(id _Nullable responseObject, NSError * error))completeHandle offlineCache:(NSString *)cacheKey
{
    if (!getDelegate().isNetworkConnenct) {
        NSString *requestURLString = [NSString stringWithFormat:@"%@%@",HOST_BASE,cacheKey];
        BOOL isCached = [[DataController getInstance] findCachedWithKey:requestURLString];
        if (isCached) {
            NSData *dataCache = [[DataController getInstance] loadCacheDataWithKey:requestURLString];
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:dataCache options:NSJSONReadingMutableContainers error:nil   ];
            completeHandle(responseObject, nil);
        }
    }else{
        [self httpRequestWithUrl:urlStr Type:type parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject ) {
            NSString *message = responseObject[@"msg"];
            NSInteger retCode = ((NSNumber *)[responseObject objectForKey:@"status"]).integerValue;
            switch (retCode) {
                case 0:
                {
                    completeHandle(responseObject[@"data"],nil);
                }
                    break;
                case HTTPCodeLogout: {
                    [[UserLocal sharedInstance] setCurrentUserInfo:nil];
                    MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
                    [getDelegate().masterNavigationController presentViewController:vc animated:YES completion:nil];
                    break;
                }
                case HTTPCodeOK: {
                    [[DataController getInstance] addCache:[NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil] andCacheKey:[NSString stringWithFormat:@"%@%@",HOST_BASE,cacheKey]];
                    completeHandle(responseObject,nil);
                    break;
                }
                default:
                    completeHandle(responseObject,[NSError errorWithDomain:@"" code:retCode userInfo:@{NSLocalizedDescriptionKey:message}]);
                    break;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSString *requestURLString = [NSString stringWithFormat:@"%@%@",HOST_BASE,cacheKey];
            BOOL isCached = [[DataController getInstance] findCachedWithKey:requestURLString];
            if (isCached) {
                NSData *dataCache = [[DataController getInstance] loadCacheDataWithKey:requestURLString];
                NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:dataCache options:NSJSONReadingMutableContainers error:nil   ];
                completeHandle(responseObject, nil);
            }
        }];
    }
}
@end
